package session

import (
	"a-common/constant"
	"a-common/core/redis"
	"a-common/utils/getid"
	"encoding/json"
	"fmt"
	"sync"
	"time"
)

var (
	sessionTemp *Session
	sessionOnce sync.Once
	rCli        = redis.New()
)

type SessionStruct struct {
	ID        int64  `json:"id"`
	Name      string `json:"name"`
	Device    string `json:"device"`
	Role      string `json:"role"`
	Timestamp int64  `json:"timestamp"`
}

type Session struct{}

func New() *Session {
	sessionOnce.Do(func() {
		sessionTemp = &Session{}
	})
	return sessionTemp
}

// Set 设置会话缓存
func (m *Session) Set(s *SessionStruct) (tokenStr string, err error) {
	gid := getid.New()
	tokenStr = gid.GetNanoId()
	if tokenStr == "" {
		err = fmt.Errorf("tokenStr error")
		return
	}
	s.Timestamp = time.Now().Unix()
	jsonSlice, err := json.Marshal(&s)
	if err != nil {
		return
	}
	// 7天
	err = rCli.SetEx(constant.LOGIN_SESSION+tokenStr, string(jsonSlice), 168*time.Hour)
	if err != nil {
		return
	}
	return
}

// Get 获取会话缓存
func (m *Session) Get(token string) (s SessionStruct, err error) {
	jsonSlice, err := rCli.Get(constant.LOGIN_SESSION + token)
	if err != nil {
		return
	}
	err = json.Unmarshal([]byte(jsonSlice.(string)), &s)
	if err != nil {
		return
	}
	// 若过期时间过半则刷新过期时间
	t := time.Unix(s.Timestamp, 0)
	diff := time.Since(t)
	// 小于三天
	if diff.Hours() > 72 {
		// 刷新redis 过期时间7天
		err = rCli.SetExpire(constant.LOGIN_SESSION+token, 168*time.Hour)
	}
	return
}

// Remove 移除会话缓存
func (m *Session) Remove(token string) error {
	return rCli.Del(constant.LOGIN_SESSION + token)
}
